<template>
</template>

<script>
export default {
    props: {
        src: {
            type: String,
            default: '',
        },
        loop: {
            type: Boolean,
            default: false,
        },
    },
    watch: {
        src(val) {
            this.loadAudioFile(val)
            .then(res => {
                this.playSound();
            });
        }
    },
    mounted() {
        const AudioContext = window.AudioContext
            || window.webkitAudioContext
            || window.mozAudioContext
            || window.msAudioContextl
        this.context = new AudioContext();
        this.source = null;
        this.audioBuffer = null;
        if (this.src !== '') {
            this.loadAudioFile(this.src)
                .then(() => {
                    console.log('start play sound');
                    this.playSound();
                });
        }
    },
    methods: {
        stopSound() {
            if (this.source) {
                this.source.stop(0);
            }
        },
        playSound() {
            this.source = this.context.createBufferSource();
            console.log('audioBuffer', this.audioBuffer);
            this.source.buffer = this.audioBuffer;
            this.source.loop = this.loop;
            this.source.connect(this.context.destination);
            console.log('this.source===>', this.source);
            this.source.start(0);
        },
        initSound(arrayBuffer) {
            return new Promise((resolve, reject) => {
                    this.context.decodeAudioData(arrayBuffer, (buffer) => {
                        console.log('buffer==>', buffer);
                    this.audioBuffer = buffer;
                    console.log('this audio buffer==>', this.audioBuffer);
                    resolve();
                }, (e) => {
                    console.log('Erro decoding file', e);
                    reject();
                });
            })
            
        },
        loadAudioFile(url) {
            return new Promise((resolve) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.responseType = 'arraybuffer';
                xhr.onload = (e) => {
                    this.initSound(xhr.response)
                    .then(resolve);
                }
                xhr.send();
            });
        }
    }
}
</script>

<style lang="less" scoped>

</style>